#include "misc.h"
#include "DEHT.h"

int main(int argc, char **argv){
	char buffer[80] = {0}, hashBuffer[80] = {0}, pswdBuffer[80] = {0};
	DEHT *ht = NULL;
	int res = 0;
	int hSize = 0;
	BasicHashFunctionPtr h = NULL;

	if (argc != 2){
		fprintf(stderr, "Error: Usage exhaustive_query <filename prefix>\n");
		return 0;
	}

	ht = load_DEHT_from_files(argv[1], hash1, hash2);
	if (ht == NULL) {
		printf("failed loading the DEHT\n");
		return 0;
	}
	parseHashFunction(ht->header.sDictionaryName, &h, &hSize);
	if (h == NULL) {
		printf("Error: Hash %s is not supported\n", ht->header.sDictionaryName);
		lock_DEHT_files(ht);
		return 0;
	}

	while (1){
		printf(">> ");
		readBuffer(buffer);
		if (strcmp(buffer, "quit") == 0)
			break;
		else if (strcmp(buffer, "") == 0)
			continue;
		if (!verifyHexa(buffer)){
			printf("Non hexa\n");
			continue;
		}
		hexa2binary(buffer, (unsigned char *)hashBuffer, 80);
		res = query_DEHT (ht, (unsigned char *)hashBuffer, hSize, (unsigned char *)pswdBuffer, 80);
		if (res == DEHT_STATUS_FAIL){
			fprintf(stderr, "%s\n", ht->sKeyfileName);
			break;
		}
		else if (res == DEHT_STATUS_NOT_NEEDED){
			printf("Sorry but this hash doesn't appears in the pre-processing\n");
			continue;
		}
		else {
			printf("Try to login with password \"%s\"\n", pswdBuffer);
			continue;
		}

	}

	lock_DEHT_files(ht);
	return 1;
}
